package com.lin.utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import com.mchange.v2.c3p0.ComboPooledDataSource;



public class JdbcUtils {
	/**
	 * 必须拥有c3p0-config.xml文件
	 */
	private  static  final DataSource  DATASOURCE = new ComboPooledDataSource();
	/**
	 * 事务专用链接
	 */
	private static ThreadLocal<Connection> local=new ThreadLocal<>();
	
	/**
	 *返回数据源 
	 */
	public static DataSource getDataSource(){
		return DATASOURCE;
	}
	
	/**
	 * c3p0返回一个连接对象
	 * @throws SQLException 
	 */
	public static Connection getConnection() throws SQLException{
		Connection connection = local.get();
		if(connection!=null) return connection;
		return DATASOURCE.getConnection();
	}
	/**
	 * 开启事务
	 * @throws SQLException 
	 */
	public static void beginTransaction() throws SQLException{
		Connection connection = local.get();
		if(connection!=null){
			throw new RuntimeException("事物已开启,请不要重复开启");
		}
		connection = getConnection();
		connection.setAutoCommit(false);
		local.set(connection);
	}
	/**
	 * 提交事务
	 * @throws SQLException 
	 */
	public static  void commitTransaction() throws SQLException{
		Connection connection = local.get();
		if(connection==null){
			throw new RuntimeException("事物未开启，无法提交");
		}
		connection.commit();
		connection.close();
		local.remove();
	}
	/**
	 * 回滚事务
	 * @throws SQLException 
	 */
	public static void rollbackTransaction() throws SQLException{
		Connection connection = local.get();
		if(connection==null){
			throw new RuntimeException("事物未开启，无法回滚");
		}
		connection.rollback();
		connection.close();
		local.remove();
	}
	
	/**
	 * 释放连接
	 * @throws SQLException 
	 */
	@SuppressWarnings("null")
	public static void releaseConnection(Connection connection) throws SQLException{
		Connection con = local.get();
		if(con==null){
			con.close();
		}
		if(con!=connection){
			con.close();
		}
	}
}
